package org.mybatis.generator.extend.all_table_generator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

/**
 * 创建一个让MBG使用的临时配置文件
 * @author lixiangke
 * @date 2017/11/22
 */
public class TempConfigGenerator {

    private String tablePrefix;
    private List<String> tableNames;

    /**
     * @param tableNames 让MBG生成代码的表名集合
     * @param tablePrefix 表名前缀, 生成实体时将忽略前缀转为驼峰命名
     */
    public TempConfigGenerator(List<String> tableNames, String tablePrefix) {
        this.tablePrefix = tablePrefix;
        this.tableNames = tableNames;
    }

    /**
     * 创建一个让MBG使用的配置文件
     */
    public String createConfig() throws Exception {
        SAXReader saxReader = new SAXReader();
        InputStream generatorConfig = new ClassPathResource("/generatorConfig.xml").getInputStream();
        Document document = saxReader.read(generatorConfig);
        Element root = document.getRootElement();
        Element context = root.element("context");
        List<Element> tables = context.elements("table");
        for (Element table : tables) {
            context.remove(table);
        }

        for (String tableName : tableNames) {
            Element newTable = DocumentHelper.createElement("table");
            newTable.addAttribute("tableName", tableName);
            newTable.addAttribute("domainObjectName", tableNameConverter(tableName));
            newTable.addAttribute("enableSelectAllSelective", "true");

            newTable.addAttribute("enableCountByExample", "false");
            newTable.addAttribute("enableUpdateByExample", "false");
            newTable.addAttribute("enableDeleteByExample", "false");
            newTable.addAttribute("enableSelectByExample", "false");
            newTable.addAttribute("selectByExampleQueryId", "false");
            context.add(newTable);
        }

        File temp = new File("tempMbgConfig.xml");
        OutputFormat format = new OutputFormat("    ", true);// 设置缩进为4个空格，并且另起一行为true
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(temp), format);
        xmlWriter.write(document);
        return temp.getAbsolutePath();
    }

    private String tableNameConverter(String tableName) {
        if ((!StringUtils.isEmpty(tablePrefix)) && tableName.startsWith(tablePrefix)) {
            tableName = tableName.replaceFirst("t", "");
        }
        if (!tableName.startsWith("_")) {
            tableName = "_" + tableName;
        }
        return HumpAndUnderlineConverter.lineToHump(tableName);
    }
}
